package com.shop.cereshop.app.service.shop.impl;

import cn.hutool.core.collection.CollUtil;
import com.shop.cereshop.app.dao.product.CereShopProductDAO;
import com.shop.cereshop.app.dao.shop.*;
import com.shop.cereshop.app.service.shop.LabelCalculationService;
import com.shop.cereshop.commons.domain.calculate.Calculate;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.domain.pay.CerePayLog;
import com.shop.cereshop.commons.domain.product.CereShopProduct;
import com.shop.cereshop.commons.domain.shop.CereBusinessTime;
import com.shop.cereshop.commons.domain.shop.CerePlatformShop;
import com.shop.cereshop.commons.domain.shop.CereShopComment;
import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service("labelcalculationservice")
public class LabelCalculationServiceImpl implements LabelCalculationService {

    @Autowired
    private CerePlatformShopDAO cerePlatformShopDAO;

    @Autowired
    private CereBusinessTimeDAO cereBusinessTimeDAO;
    @Autowired
    private CereShopCommentDAO cereShopCommentDAO;

    @Autowired
    private CereShopReturnDAO cereShopReturnDAO;

    @Autowired
    private CereShopPersonalDAO cereShopPersonalDAO;

    @Autowired
    private CereShopProductDAO cereShopProductDAO;


    @Override
    public List<Calculate> shopTitleCalculation() {
        XxlJobHelper.log("开始计算店铺的营业时间");
        // 查询所有的店铺id
        List<Long> shopIds = cerePlatformShopDAO.selectAllShopId();


        XxlJobHelper.log("共找到 " + shopIds.size() + " 个店铺");
        if (CollUtil.isEmpty(shopIds)) {
            return null;
        }
        List<Calculate> calculateList = new ArrayList<>();

        Map<Long, Integer> allWeekToUseMap = calculateAllWeekToUse();
        Map<Long, Integer> shopAvgStarMap = getShopAvgStar();
        Map<Long, Integer> returnPayNotConsidered = getReturnPayNotConsidered();
        Map<Long, Integer> hotShop = getHotShop();
        Map<Long, Integer> commentNumber = getRefundSafe();
        Map<Long, BigDecimal> peopleConsume = getPeopleConsume();

        for (Long shopId : shopIds) {
//            Integer i = allWeekToUseMap.get(shopId);
            Calculate calculate = new Calculate();
            calculate.setShopAllWeekToUer(allWeekToUseMap.get(shopId) == null ? 0 : allWeekToUseMap.get(shopId));
            calculate.setShopGoodLikeWater(shopAvgStarMap.get(shopId) == null ? 0 : shopAvgStarMap.get(shopId));
            calculate.setRefundSafe(returnPayNotConsidered.get(shopId) == null ? 0 : returnPayNotConsidered.get(shopId));
            calculate.setHotGoods(hotShop.get(shopId) == null ? 0 : hotShop.get(shopId));
            calculate.setShopAverageConsumption(peopleConsume.get(shopId) == null ? BigDecimal.valueOf(0) : peopleConsume.get(shopId));
            calculate.setCommentNumber(commentNumber.get(shopId) == null ? 0 : commentNumber.get(shopId));
            calculate.setShopId(shopId);
            calculateList.add(calculate);
        }
        return calculateList;
    }


    Map<Long, Integer> calculateAllWeekToUse() {
        // 获取所有店铺的营业时间 key: shopId, value: 是否全周可用
        Map<Long, Integer> allWeekToUse = new HashMap<>();
        List<CereBusinessTime> bussinessTimes = cereBusinessTimeDAO.selectList(null);
        XxlJobHelper.log("共查询到 " + bussinessTimes.size() + " 条营业时间记录");
        if (CollUtil.isNotEmpty(bussinessTimes)) {
            // 按店铺ID分组营业时间数据，便于后续处理
            Map<Long, List<CereBusinessTime>> businessTimeByShop = bussinessTimes.stream().collect(Collectors.groupingBy(CereBusinessTime::getShopId));
            // 处理每个店铺的营业时间数据
            for (Long shopId : businessTimeByShop.keySet()) {
                List<CereBusinessTime> cereBussinessTimes = businessTimeByShop.get(shopId);
                if (CollUtil.isNotEmpty(cereBussinessTimes)) {
                    // 判断是否全周可用
                    Integer isAllWeekAvailable = checkIfAllWeekAvailable(cereBussinessTimes);
                    allWeekToUse.put(shopId, isAllWeekAvailable);
                    XxlJobHelper.log("店铺ID: " + shopId + ", 营业时间记录数: " + cereBussinessTimes.size() + ", 是否全周可用: " + isAllWeekAvailable);
                }
            }
        }
        return allWeekToUse;
    }


    /**
     * 获取店铺的评价
     *
     * @return 店铺的平均星
     */
    /**
     * 获取店铺的评价
     *
     * @return 店铺的平均星
     */
    private Map<Long, Integer> getShopAvgStar() {
        // 获取店铺的评价 key: shopId, value: 平均星
        Map<Long, Integer> shopAvgStarMap = new HashMap<>();
        List<CereShopComment> shopAvgStar = cereShopCommentDAO.getShopAvgStar();
        if (CollUtil.isNotEmpty(shopAvgStar)) {
            for (CereShopComment shopComment : shopAvgStar) {
                // 添加空值检查，防止 NullPointerException
                if (shopComment != null &&
                        shopComment.getScore() != null &&
                        shopComment.getShopId() != null &&
                        shopComment.getScore() >= 4) {
                    shopAvgStarMap.put(shopComment.getShopId(), 1);
                }
            }
        }
        return shopAvgStarMap;
    }



    /**
     * 获取店铺退款无忧标签
     */
    public Map<Long, Integer> getReturnPayNotConsidered() {
        HashMap<Long, Integer> ShopReturnPayNotConsidered = new HashMap<>();
        List<CerePayLog> returnNotConsider = cereShopReturnDAO.getReturnNotConsider();
        if (CollUtil.isNotEmpty(returnNotConsider)) {
            for (CerePayLog returnNotConsiders : returnNotConsider) {
                if (returnNotConsiders.getReturnMoney() >= 0.3) {
                    ShopReturnPayNotConsidered.put(returnNotConsiders.getShopId(), 1);
                } else {
                    ShopReturnPayNotConsidered.put(returnNotConsiders.getShopId(), 0);
                }
            }
        }
        return ShopReturnPayNotConsidered;
    }


    /**
     * 热销店铺
     */
    public Map<Long, Integer> getHotShop() {

        Map<Long, Integer> shopHot = new HashMap<>();
        List<CerePlatformShop> hotShop = cerePlatformShopDAO.getHotShopTopTen();
        if (CollUtil.isNotEmpty(hotShop)) {
            for (CerePlatformShop shop : hotShop) {
                if (shop != null) {
                    shopHot.put(shop.getShopId(), 1);

                } else {

                    shopHot.put(shop.getShopId(), 0);
                }

            }
        }

        return shopHot;
    }


    /**
     * 获取店铺评论数量
     */
    public Map<Long, Integer> getRefundSafe() {
        Map<Long, Integer> shopCommentmap = new HashMap<>();
        List<CereShopComment> shopComments = cereShopCommentDAO.getShopComments();
        if (CollUtil.isNotEmpty(shopComments)) {
            for (CereShopComment shopComment : shopComments) {
                shopCommentmap.put(shopComment.getShopId(), shopComment.getCommentCount());
            }
        }
        return shopCommentmap;
    }


    /**
     * 获取店铺人均消费
     */

    public Map<Long, BigDecimal> getPeopleConsume() {
        HashMap<Long, BigDecimal> shopPeopleConsume = new HashMap<>();
        List<CereShopOrder> peopleConsume = cereShopPersonalDAO.getPeopleConsume();
        if (CollUtil.isNotEmpty(peopleConsume)) {
            for (CereShopOrder shopOrder : peopleConsume) {
                shopPeopleConsume.put(shopOrder.getShopId(), shopOrder.getAvgPrice());

            }
        }
        return shopPeopleConsume;
    }


    /**
     * 检查店铺或是商品是否全周可用
     *
     * @param shopBusinessTimes 店铺的营业时间列表
     * @return 是否全周可用
     */
    private Integer checkIfAllWeekAvailable(List<CereBusinessTime> shopBusinessTimes) {
        // 如果集合长度为7，则认为是全周可用
        if (shopBusinessTimes.size() == 7) {
            return 1;
        }
        return 0;
    }


    /**
     * 商品有关标签
     *
     * @return
     */
    @Override
    public List<Calculate> productTitleCalculation() {
        List<Calculate> calculates = new ArrayList<>();
        Map<Long, Integer> productAvgStar = getProductAvgStar();
        //热销商品
        Map<Long, Integer> priceGood = getPriceGood();
        //价格实惠
        Map<Long, Integer> shopGoodPrice = getShopGoodPrice();
        Map<Long, Integer> productAllWeekStatus = getProductAllWeekStatus();
        //        查询所有的商品id
        List<Long> productIds = cereShopProductDAO.selectSAllhopId();
        for (Long productId : productIds) {
            Calculate calculate = new Calculate();
            calculate.setProductId(productId);
            calculate.setHotProduct(priceGood.get(productId) == null ? 0 : priceGood.get(productId));
            calculate.setProductGoodLikeWater(productAvgStar.get(productId) == null ? 0 : productAvgStar.get(productId));
            calculate.setPriceGood(shopGoodPrice.get(productId) == null ? 0 : shopGoodPrice.get(productId));
            calculate.setProductAllWeekToUer(productAllWeekStatus.get(productId) == null ? 0 : productAllWeekStatus.get(productId));
            calculates.add(calculate);
        }
        return calculates;
    }


    /**
     * 获取商品是否好评如潮
     */
    public Map<Long, Integer> getProductAvgStar() {
        Map<Long, Integer> productAvgStar = new HashMap<>();
        List<CereShopComment> productAvgStars = cereShopCommentDAO.getProductAvgStar();
        if (CollUtil.isNotEmpty(productAvgStars)) {
            for (CereShopComment productComment : productAvgStars) {
                // 添加空值检查
                if (productComment != null &&
                        productComment.getScore() != null &&
                        productComment.getProductId() != null &&
                        productComment.getScore() >= 4) {
                    productAvgStar.put(productComment.getProductId(), 1);
                }
            }
        }
        return productAvgStar;
    }



    /**
     * 热销商品
     */
    public Map<Long, Integer> getPriceGood() {
        Map<Long, Integer> productPriceGood = new HashMap<>();
        List<CereShopProduct> productHotGood = cereShopProductDAO.getProductHootGood();
        if (CollUtil.isNotEmpty(productHotGood)) {
            for (CereShopProduct productGood : productHotGood) {
                if (productGood != null) {
                    productPriceGood.put(productGood.getProductId(), 1);
                } else {
                    productPriceGood.put(productGood.getProductId(), 0);
                }
            }
        }
        return productPriceGood;
    }


    /**
     * 商品价格实惠
     */
    public Map<Long, Integer> getShopGoodPrice() {
        Map<Long, Integer> shopGoodPrice = new HashMap<>();
        List<CereShopProduct> productHootGood = cereShopProductDAO.getPriceGoood();
        if (CollUtil.isNotEmpty(productHootGood)) {
            for (CereShopProduct cereShopProduct : productHootGood) {
                shopGoodPrice.put(cereShopProduct.getProductId(), cereShopProduct.getStatus());
            }
        }
        return shopGoodPrice;

    }

    /**
     * 商品是否全周可用
     */
    public Map<Long, Integer> getProductAllWeekStatus() {
        // 1. 获取店铺是否全周可用的映射（Key=店铺ID，Value=1/0）
        Map<Long, Integer> shopAllWeekMap = calculateAllWeekToUse();

        // 2. 查询所有商品的【商品ID】和【所属店铺ID】（关键：必须关联 shop_id）
        List<CereShopProduct> allProducts = cereShopProductDAO.selectAllProductWithShopId();

        // 3. 构建商品ID到全周可用状态的映射
        Map<Long, Integer> productStatusMap = new HashMap<>();
        for (CereShopProduct product : allProducts) {
            Long productId = product.getProductId(); // 商品ID
            Long shopId = product.getShopId();       // 商品所属店铺ID

            // 3.1 从店铺映射中获取该店铺的全周可用状态（默认0：若店铺不存在或状态未知）
            Integer shopStatus = shopAllWeekMap.getOrDefault(shopId, 0);

            // 3.2 将商品ID和对应的状态放入结果Map
            productStatusMap.put(productId, shopStatus);
        }

        return productStatusMap;
    }

}

